from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import JsonResponse
from django.db import transaction
from .models import Order, OrderItem
from merchants.models import MenuItem
from datetime import datetime
from django.core.paginator import Paginator
from .forms import OrderRatingForm

# Create your views here.

# 我的订单视图

@login_required
def my_orders(request):
    """我的订单列表视图"""
    status = request.GET.get('status', 'all')
    orders = Order.objects.filter(user=request.user)
    
    if status != 'all':
        orders = orders.filter(status=status)
    
    orders = orders.order_by('-created_at')
    
    # 分页
    paginator = Paginator(orders, 10)  # 每页显示10条
    page = request.GET.get('page')
    orders = paginator.get_page(page)
    
    context = {
        'orders': orders,
        'status': status
    }
    return render(request, 'orders/order_list.html', context)

@login_required
def create_order(request):
    """创建新订单"""
    if request.method == 'POST':
        try:
            with transaction.atomic():
                # 获取购物车数据
                cart_items = request.POST.getlist('cart_items[]')
                merchant_id = request.POST.get('merchant_id')
                address_id = request.POST.get('address_id')
                note = request.POST.get('note', '')

                # 创建订单
                order = Order.objects.create(
                    user=request.user,
                    merchant_id=merchant_id,
                    address_id=address_id,
                    note=note,
                    status='pending'
                )

                # 添加订单项
                total_amount = 0
                for item_data in cart_items:
                    menu_item = MenuItem.objects.get(id=item_data['item_id'])
                    quantity = item_data['quantity']
                    price = menu_item.price
                    
                    OrderItem.objects.create(
                        order=order,
                        menu_item=menu_item,
                        quantity=quantity,
                        price=price
                    )
                    total_amount += price * quantity

                # 更新订单总金额
                order.total_amount = total_amount
                order.save()

                return JsonResponse({
                    'status': 'success',
                    'order_id': order.id
                })
        except Exception as e:
            return JsonResponse({
                'status': 'error',
                'message': str(e)
            })
    return JsonResponse({'status': 'error', 'message': '无效的请求方法'})

@login_required
def order_detail(request, order_id):
    """订单详情视图"""
    order = get_object_or_404(Order, id=order_id, user=request.user)
    return render(request, 'orders/order_detail.html', {'order': order})

@login_required
def cancel_order(request, order_id):
    """取消订单视图"""
    order = get_object_or_404(Order, id=order_id, user=request.user)
    if order.status == 'pending':
        order.status = 'cancelled'
        order.save()
        messages.success(request, '订单已取消')
    else:
        messages.error(request, '只能取消待处理的订单')
    return redirect('my_orders')

@login_required
def rate_order(request, order_id):
    """订单评价视图"""
    order = get_object_or_404(Order, id=order_id, user=request.user)
    
    if request.method == 'POST':
        form = OrderRatingForm(request.POST)
        if form.is_valid():
            order.rating = form.cleaned_data['rating']
            order.review = form.cleaned_data['review']
            order.is_rated = True
            order.save()
            messages.success(request, '评价提交成功')
            return redirect('my_orders')
    else:
        form = OrderRatingForm()
    
    return render(request, 'orders/rate_order.html', {
        'order': order,
        'form': form
    })

@login_required
def order_history(request):
    """订单历史"""
    orders = Order.objects.filter(
        user=request.user
    ).exclude(
        status='pending'
    ).order_by('-created_at')
    return render(request, 'order_history.html', {'orders': orders})
